<?php
/**
 * Created by PhpStorm.
 * User: Knight
 * Date: 2018/3/15
 * Time: 10:34
 */

namespace app\api\util;


class RandomUtil
{
    /**
     * 随机字符串生成
     * @param int $length
     * @return string
     */
    public static function randomStr( $length = 4 ) {
        // 密码字符集，可任意添加你需要的字符
        $chars1 = '0123456789';
//        $chars2 = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
//        $chars3 = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $rod = '';
//        $rod .= $chars2[ mt_rand(0, strlen($chars2) - 1) ];
//        $rod .= $chars1[ mt_rand(0, strlen($chars1) - 1) ];
        for ( $i = 0; $i < $length; $i++ )
        {
            // 这里提供两种字符获取方式
            // 第一种是使用 substr 截取$chars中的任意一位字符；
            // 第二种是取字符数组 $chars 的任意元素
            // $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
            $rod .= $chars1[ mt_rand(0, strlen($chars1) - 1) ];
        }
        return $rod;
    }
}